/**
 * 
 */
package com.gr.staffpm.charts;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.wicket.ResourceReference;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebComponent;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.parser.XmlTag;

import com.gr.staffpm.css.CssScope;
import com.gr.staffpm.datatypes.Project;
import com.gr.staffpm.js.StaffPMJSScope;
import com.gr.staffpm.pages.projects.TasksTabPanel;


/**
 * @author Graham Rhodes 26 Apr 2011 18:14:05
 */
public class GanttPanel extends Panel implements IHeaderContributor {

    private static final long serialVersionUID = 1L;
    private final Project project;

    public GanttPanel(String id, Project project) {
        super(id);
        this.project = project;
        add(new WebComponent("ganttScript") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {
                replaceComponentTagBody(markupStream, openTag, getGanttScript());
            }

            @Override
            protected void onComponentTag(ComponentTag tag) {
                super.onComponentTag(tag);
                // always transform the tag to <span></span> so even labels defined as <span/> render
                tag.setType(XmlTag.OPEN);
            }
        });
    }

    /* (non-Javadoc)
     * @see org.apache.wicket.markup.html.IHeaderContributor#renderHead(org.apache.wicket.markup.html.IHeaderResponse)
     */
    @Override
    public void renderHead(IHeaderResponse response) {
        response.renderCSSReference(new ResourceReference(CssScope.class, "extjs/sch-gantt-all.css"));
        response.renderJavascriptReference(new ResourceReference(StaffPMJSScope.class, "extjs/sch-gantt-base-debug.js"));
        response.renderJavascriptReference(new ResourceReference(StaffPMJSScope.class, "extjs/sch-gantt-all-debug.js"));
    }

    /**
     * Returns Javascript code which renders the gantt chart.
     * @throws RuntimeException if gantt.js cannot be loaded.
     */
    private String getGanttScript() {
        try {
            final String str = getResourceContents(TasksTabPanel.class, "gantt.js");

            return str.format(str, String.valueOf(project.getProjectId()));
        } catch (IOException e) {
            throw new RuntimeException("Unable to load gantt.js", e);
        }
    }

    /**
     * Returns the contents of the given resource.
     * @param location The resource path.
     * @return The resource's content.
     * @throws FileNotFoundException If the resource cannot be found.
     * @throws IOException If anything goes wrong while reading the resource.
     */
    private static String getResourceContents(Class<?> clazz, String location) throws IOException {
        InputStream in = clazz.getResourceAsStream(location);
        if (in == null)
            throw new FileNotFoundException("'" + location + "' not found.");
        return getStreamContents(new InputStreamReader(in));
    }

    /**
     * Returns the complete content of the given stream.
     * @throws IOException If anything goes wrong while reading the stream.
     */
    private static String getStreamContents(InputStreamReader inputStreamReader) throws IOException {
        StringBuffer str = new StringBuffer();
        BufferedReader in = new BufferedReader(inputStreamReader);

        while (true) {
            String line = in.readLine();
            if (line == null)
                break;
            str.append(line);
            str.append("\n");
        }

        return str.toString();
    }

}
